package com.usian.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.config.NameExistsException;
import com.usian.mapper.SetMealMapper;
import com.usian.mapper.SetmealDishMapper;
import com.usian.pojo.Setmeal;
import com.usian.pojo.SetmealDish;
import com.usian.pojo.SetmealDto;
import com.usian.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetMealMapper setMealMapper;


    @Transactional
    @Override
    public void save(SetmealDto setmealDto) {
        setmealDto.setUpdateTime(LocalDateTime.now());
        setmealDto.setCreateTime(LocalDateTime.now());
        setmealDto.setStatus(1);
        setMealMapper.insert(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId()); //所属的套餐
            setmealDish.setCreateUser(setmealDto.getCreateUser());
            setmealDish.setUpdateUser(setmealDto.getUpdateUser());
            setmealDish.setCreateTime(setmealDto.getCreateTime());
            setmealDish.setUpdateTime(setmealDto.getUpdateTime());
            setmealDish.setSort(0); //排序
            setmealDishMapper.insert(setmealDish);
        }
    }

    @Override
    public Page<SetmealDto> findByPage(Integer page, Integer pageSize, String name) {
        Page<SetmealDto> page1 = new Page<>(page,pageSize);
        List<SetmealDto> list = setMealMapper.findAll(page1,name);
        return page1.setRecords(list);
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        for (Long id : ids) {
            Setmeal setmeal = setMealMapper.selectById(id);
            if(setmeal.getStatus()==0){
                setMealMapper.deleteById(id);
                setmealDishMapper.deleteBySetmealId(id);
            }else{
                throw new NameExistsException("选择的套餐中有在售的套餐不能删除");
            }
        }
    }

    @Override
    public void updateByStatus(Long[] ids) {
        for (Long id : ids
        ) {
            Setmeal setmeal = setMealMapper.selectById(id);
            setmeal.setStatus(1);
            setMealMapper.updateById(setmeal);
        }
    }

    @Override
    public void updateByStatuss(Long[] ids) {
        for (Long id : ids
        ) {
            Setmeal setmeal = setMealMapper.selectById(id);
            setmeal.setStatus(0);
            setMealMapper.updateById(setmeal);
        }
    }

}
